// pages/index/index.js
const app = getApp();
//解析html
const WxParse = require('../../wxParse/wxParse.js');

// 引入SDK核心类
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var key = app.globalData.qqmapsdk;
var qqmapsdk = new QQMapWX({
  key: key
});

import Api from '../../utils/http';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    webSiteUrl: app.globalData.webSiteUrl,
    identityStatus: 1, //0为管理员身份，1为部门管理员
    tabBarIndex: 0, //tabBar对应的索引
    userStatus: 2, //当identityStatus 为1时，userStatus为1是部门管理员，为2是用户
    identity: '管理员',
    identityArr: ['单位管理员', '部门管理员'],
    location: [], //当前定位
    msg: '', //未读取消息
    profit: '',
    profitMsg: 0,
    userid: '', //
    banner: [], //轮播图
    newsList: [], //新闻资讯
    backList: [], //分类小知识
    sunList: [], //晒一晒
    nearbyPoint: [], //附近投放点
    state: '', //答题状态
    usertype: null, //切换状态
    userinfo: '', //个人信息
    userInfo: '', //切换用户信息
    result:null,
    adminNav: [{
        title: '呼叫回收',
        url: '/images/unit/nav01.png',
        tap: 'callRecovery'
      },
      {
        title: '呼叫领袋',
        url: '/images/unit/nav02.png',
        tap: 'callBag'
      },
      {
        title: '回收价格',
        url: '/images/unit/nav03.png',
        tap: 'recyclingKinds'
      },
      {
        title: '使用指南',
        url: '/images/unit/nav04.png',
        tap: 'toUseGuide'
      },
    ], //管理员
    userNav: [{
        title: '扫码开门',
        url: '/images/user/nav05.png',
        tap: 'toOpenCode'
      },
      {
        title: '快捷领袋',
        url: '/images/unit/nav02.png',
        tap: 'toGetQuickly'
      },
      {
        title: '回收价格',
        url: '/images/unit/nav03.png',
        tap: 'recyclingKinds'
      },
      {
        title: '使用指南',
        url: '/images/unit/nav04.png',
        tap: 'toUseGuide'
      },
    ], //用户 and 部门管理员

  },
  //切换身份
  identityPicker: function (e) {
    console.log('当前身份(0为管理员身份，1为用户身份)，携带值为', e.detail.value)
    this.setData({
      identityStatus: e.detail.value
    });
  },
  //切换用户
  switch: function () {
    this.getroleSwitch();
  },
  //管理员 - >设置
  toAdminSetting: function () {
    wx.navigateTo({
      url: '/pages/admin/adminSetting/setting/setting',
    })
  },
  //部门管理员 或者 用户 - >消息
  toUserMsg: function () {
    wx.navigateTo({
      url: '/pages/user/user/userMsg/userMsg',
    })
  },
  //待确认回收
  recovery: function (e) {
    this.getSureSend(e)
  },
  //待确认发袋
  hairbag: function (e) {
    this.getSureSend(e)
  },
  //跳转投放列表
  toLaunchList: function (e) {
    wx.navigateTo({
      url: '/pages/user/putInPoint/pointIndex/pointIndex',
    })
  },
  //跳转投放详情
  toLaunchDetails: function (e) {
    var that = this
    var {
      nearbyPoint
    } = that.data
    let result=wx.getStorageSync('result')
    console.log("1111111111111111")
    console.log(result)
    console.log(typeof result)
    console.log("1111111111111111")
    var longitude = result.result.location.lng
    var latitude = result.result.location.lat
    let index = e.currentTarget.dataset.index
    console.log(e.currentTarget.dataset)
    var lid = nearbyPoint[index].id
    wx.navigateTo({
      url: `/pages/user/putInPoint/pointDetail/pointDetail?lid=${lid}&longitude=${longitude}&latitude=${latitude}`,
    })
  },
  //跳转发现、资讯列表
  toNewsList: function (e) {
    var that = this;
    console.log(that.data)
    if (that.data.userid.user_type == 3) {
      wx.navigateTo({
        url: '/pages/user/find/timeInfo/timeInfo',
      })
    } else {
      wx.navigateTo({
        url: '/pages/user/find/findIndex/findIndex',
      })
    }

  },
  //跳转新闻详情
  toNewsDetails: function (e) {
    var that = this;
    var {
      newsList
    } = that.data
    let index = e.currentTarget.dataset.index
    console.log(e.currentTarget.dataset)
    var lid = newsList[index].id
    var type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: `/pages/news/newsListDetails/newsListDetails?lid=${lid}&type=${type}`,
    })
  },
  //跳转到小知识详情
  toBackDetails: function (e) {
    var that = this;
    var {
      backList
    } = that.data
    let index = e.currentTarget.dataset.index
    console.log(e.currentTarget.dataset)
    var lid = backList[index].id
    var type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: `/pages/news/newsListDetails/newsListDetails?lid=${lid}&type=${type}`,
    })
  },
  //跳转晒一晒详情
  toSunDetails: function (e) {
    var that = this;
    var {
      sunList
    } = that.data
    let index = e.currentTarget.dataset.index
    console.log(e.currentTarget.dataset)
    var lid = sunList[index].id
    var type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: `/pages/news/newsListDetails/newsListDetails?lid=${lid}&type=${type}`,
    })
  },
  //呼叫领袋
  callBag: function () {
    var that = this;
    let uid = wx.getStorageSync('userid')
    var param = {
      uid: uid.id,
      user_type: 3,
      type: 1,
    }
    console.log(param)
    Api.ajax('/app/zindex/callRecycle', param).then(res => {
      console.log(res)
      if (res.code == 200) {
        wx.showToast({
          title: '呼叫成功，请等待',
          icon: 'success',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '请勿重复呼叫',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  //呼叫回收
  callRecovery: function () {
    var that = this;
    let uid = wx.getStorageSync('userid')
    var param = {
      uid: uid.uid,
      user_type: 3,
      type: 2,
    }
    console.log(param)
    Api.ajax('/app/zindex/callRecycle', param).then(res => {
      console.log(res)
      if (res.code == 200) {
        wx.showToast({
          title: '呼叫成功',
          icon: 'success',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '请勿重复呼叫',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  //回收价格
  recyclingKinds: function () {
    wx.navigateTo({
      url: '/pages/recycling/recyclingKinds/recyclingKinds',
    })
  },
  //使用指南
  toUseGuide: function () {
    wx.navigateTo({
      url: '/pages/useGuide/guideList/guideList',
    })
  },
  //跳转 快捷领袋
  toGetQuickly: function () {
    var that = this;
    console.log(that.data);
    let verification = that.data.userinfo.verification;
    let num = that.data.userinfo.recyc_bag_num;
    let user_type=that.data.userinfo.user_type;
    if (user_type==1) {
      if (verification != 0) {
        if (num == 0) {
          wx.showModal({
            title: '提示',
            content: '数量不足，请先购买',
            confirmText: '确定购买',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/user/user/userRecyclingBuy/userRecyclingBuy',
                })
              }
            }
          })
        } else {
          wx.navigateTo({
            url: '/pages/user/user/userRecyclingGet/userRecyclingGet',
          })
        }
      } else {
        wx.showModal({
          title: '提示',
          content: '当前用户未认证，点击确定前往认证',
          confirmText: '确定',
          showCancel: false,
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/user/user/mobileAuth/mobileAuth',
              })
            }
          }
        })
      }
    }else if(user_type==2){
      if (num == 0) {
        wx.showToast({
          title: '数量不足，请联系单位管理员',
          icon:'none',
          duration:2000
        })
      } else {
        wx.navigateTo({
          url: '/pages/user/user/userRecyclingGet/userRecyclingGet',
        })
      }
    }
  },
  //跳转 扫码开门二维码
  toOpenCode: function () {
    var that = this;
    let uid = wx.getStorageSync('userid');
    if (uid.user_type == 1) {
      wx.navigateTo({
        url: '/pages/user/user/userCode/userCode?codeType=2',
      })
    } else {
      wx.navigateTo({
        url: '/pages/user/user/userCode/userCode?codeType=1',
      })
    }

  },
  //跳转 去答题
  toAnswer: function () {
    var that = this;
    console.log(that.data);
    let states = that.data.state.status;

    if (states == 1) {
      wx.navigateTo({
        url: `/pages/dayQuestion/dayQuestion/dayQuestion?states=${states}`,
      })
    } else {

      wx.navigateTo({
        url: `/pages/dayQuestion/dayQuestion/dayQuestion?states=${states}`,
      })
    }

  },
  //跳转 答题排行榜
  toRanking: function () {
    wx.navigateTo({
      url: '/pages/dayQuestion/questionRanking/questionRanking',
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      options: options
    });



  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    console.log(111111);

    wx.hideHomeButton({
      success: function () {
        console.log('成功了');
      },
    })
    that.getNews();
    that.getSun();
    that.getBack();
    
    that.getlogin();
    that.getCurrentLocation();

  },

  //个人信息
  getuserInfo: function () {
    var that = this;
    let uid = wx.getStorageSync('userid');
    var param = {
      uid: uid.id,
      user_type: uid.user_type,
    };
    Api.ajax("/app/Zpersonalcenter/userInfo", param).then(res => {
      console.log(res)
      console.log('getuserInfo');
      if (res.code == 200) {
        console.log(111111111)
        if (res.data.user_type == 2 && res.data.verification_depart == 0) {
          wx.showModal({
            title: '提示',
            content: '该用户身份未认证，请认证',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/user/user/identityAuth/identityAuth',
                })
              }
            }
          })
          console.log(2222222222222)
        } else if (res.data.user_type == 3 && res.data.verification_manage == 0) {
          wx.showModal({
            title: '提示',
            content: '该用户身份未认证，请认证',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/user/user/identityAuth/identityAuth',
                })
              }
            }
          })
        }
        that.setData({
          userinfo: res.data
        })

      }
    })
  },
  //切换用户
  getroleSwitch: function (e) {
    var that = this;
    let uid = wx.getStorageSync('userid');
    var param = {
      uid: uid.id,
      user_type: uid.user_type,
      type: 1,
    }
    console.log(param)
    Api.ajax('/app/Zindexmanage/roleSwitch', param).then(res => {
      console.log(res)
      if (res.code == 200) {
        wx.setStorageSync('userid', res.data);
        that.setData({
          userInfo: res.data
        })
        setTimeout(function () {
          wx.reLaunch({
            url: '/pages/index/index',
          })
        }, 1000)
        wx.showToast({
          title: '网络慢，请刷新',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  //登录信息接口
  getlogin: function (options) {
    var that = this;
    let opid = wx.getStorageSync('openid');
    let usertext = wx.getStorageSync('userInfo');
    console.log('ddd', opid, usertext)
    var param = {
      openid: opid,
      nickname: usertext.nickName,
      head_icon: usertext.avatarUrl
    }
    console.log(param)
    Api.ajax("/app/Zaccount/three_Login", param).then(res => {
      console.log(res)
      console.log('getLogin')
      if (res.code == 200) {
        that.setData({
          userid: res.data,
        });
        wx.setStorageSync('userid', res.data)
        var identityStatus = that.data.identityStatus;
        var userStatus = that.data.userStatus;
        if (res.data.user_type == 1) {
          identityStatus = 1;
          userStatus = 2;
        } else if (res.data.user_type == 2) {
          identityStatus = 1;
          userStatus = 1;
        } else if (res.data.user_type == 3) {
          identityStatus = 0;
          userStatus = 1;
        }
        that.setData({
          identityStatus: identityStatus,
          userStatus: userStatus,
        });
        that.getIndex();
        that.getBanner();
        that.getuserInfo();
        // that.getPosition();
        that.getAnswerStatus();
      }
    })
  },
  //首页banner
  getBanner: function () {
    var that = this;
    Api.ajax("/app/Zindex/banner").then(res => {
      console.log('getBanner');
      that.setData({
        banner: res
      })
    })
  },
  //最近投放点
  getPosition: function (e) {
    var that = this;
    var uid = wx.getStorageSync('userid');
    var param = {
      uid: uid.id,
      user_type: uid.user_type,
      pageNum: '1',
      pageSize: '3',
      longitude: that.data.lng,
      latitude: that.data.lat,
    }
    console.log(param)
    Api.ajax("/app/Zlaunchpoint/pointlist", param).then(res => {
      console.log(res)
      console.log('getPosition');
      if (res.code == 200) {
        that.setData({
          nearbyPoint: res.data,
          location: res.data[0]
        });
      }
    })
  },
  //新闻
  getNews: function () {
    var that = this;
    var param = {
      type: 1,
      pageNum: 1,
      pageSize: 1,
    }
    Api.ajax("/app/Zarticle/articleList", param).then(res => {
      console.log('getNews');
      console.log(res)
      if (res.code == 200) {
        that.setData({
          newsList: res.data
        });
      }
    })
  },
  //、晒一晒
  getSun: function () {
    var that = this;
    var param = {
      type: 3,
      pageNum: 1,
      pageSize: 1,
    }
    Api.ajax("/app/Zarticle/articleList", param).then(res => {
      console.log(res)
      console.log('getSun');
      if (res.code == 200) {
        // var newsArr = res.data;
        // for (let i = 0; i < newsArr.length; i++) {
        //   WxParse.wxParse('title' + i, 'html', newsArr[i].title, that);
        //   if (i === newsArr.length - 1) {
        //     WxParse.wxParseTemArray("newsArray",'title', newsArr.length, that)
        //   }
        // }
        that.setData({
          sunList: res.data
        });
      }
    })
  },
  //待确认回收、发袋
  getSureSend: function (e) {
    var that = this;
    var uid = wx.getStorageSync('userid');
    var type = e.currentTarget.dataset.idtype;
    var param = {
      uid: uid.id,
      type: type
    }
    console.log(param)
    Api.ajax('/app/Zmanage/sureSend', param).then(res => {
      console.log('getSureSend');
      console.log(res)
      if (res.code == 200) {
        wx.showToast({
          title: '确认成功',
          icon: 'none',
          duration: 1000
        })
      } else {
        wx.showToast({
          title: '操作失败',
          icon: 'none',
          duration: 1000
        })
      }
    })
  },
  //分类小知识
  getBack: function () {
    var that = this;
    var param = {
      type: 4,
      pageNum: 1,
      pageSize: 1,
    }
    Api.ajax("/app/Zarticle/articleList", param).then(res => {
      console.log('getBack');
      console.log(res)
      if (res.code == 200) {
        that.setData({
          backList: res.data
        });
      }
    })
  },

  //首页数据
  getIndex: function () {
    var that = this;
    let uid = wx.getStorageSync('userid');
    var param = {
      uid: uid.id,
      user_type: uid.user_type
    }
    console.log(param)
    Api.ajax("/app/Zindex/index", param).then(res => {
      console.log('getIndex');
      console.log(res)
      if (res.code == 200) {
        that.setData({
          profit: res.data,
          profitMsg: res.data.msg
        });
      }
    })
  },
  //答题状态
  getAnswerStatus: function () {
    var that = this;
    let uid = wx.getStorageSync('userid')
    var param = {
      uid: uid.id
    }
    console.log(param)
    Api.ajax('/app/Zarticle/todayProblem', param).then(res => {
      console.log('getAnswerStatus');
      console.log(res)
      if (res.code == 200) {

        that.setData({
          state: res.data
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getlogin();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //获取当前定位
  getCurrentLocation: function () {
    var _this = this;
    qqmapsdk.reverseGeocoder({
      //位置坐标，默认获取当前位置，非必须参数
      //Object格式
      // location: {
      //   latitude: 39.984060,
      //   longitude: 116.307520
      // },
      //String格式
      // location: '39.984060,116.307520',

      //location: '', //获取表单传入的位置坐标,不填默认当前位置,示例为string格式
      // get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
      success: function (res) { //成功后的回调
        console.log(res);
        wx.setStorageSync('result', res)
        var result = res.result;
        wx.setStorageSync('latLng', result.location)
        _this.setData({
          lat: result.location.lat,
          lng: result.location.lng,
        })
        _this.getPosition();
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        // console.log(res);
        wx.hideLoading();
      }
    })
  },
})